package utils

type goTaskItem struct {
	fn   func(args ...interface{})
	args []interface{}
}

type GoTaskWoker struct {
	Terminated int8
	owner      *GoTask
	tasklst    chan *goTaskItem
}

func NewGoTaskWoker(owner *GoTask, maxCache int) *GoTaskWoker {
	rval := &GoTaskWoker{
		owner:   owner,
		tasklst: make(chan *goTaskItem, maxCache),
	}
	rval.start()
	return rval
}

func (this *GoTaskWoker) innerWork() {
	if GoFunCatchException {
		defer PanicHandler()
	}
break_for:
	for {
		select {
		case itm := <-this.tasklst:
			if itm == nil {
				break break_for
			}
			if this.Terminated == 0 {
				itm.fn(itm.args...)
				this.owner.onWorkerDone(this)
			}
		}
	}
}

func (this *GoTaskWoker) start() {
	go this.innerWork()
}

func (this *GoTaskWoker) Stop() {
	this.Terminated = 1
	this.tasklst <- nil
}

func (this *GoTaskWoker) PushTask(fn func(args ...interface{}), args ...interface{}) {
	itm := &goTaskItem{fn: fn, args: args}
	this.tasklst <- itm
}
